<template>
  <el-dialog
    title="报销申请单"
    :visible.sync="show"
    width="1080px"
    append-to-body
    @close="dialogClose"
  >
    <el-form ref="formRef" :model="editForm" :rules="formRules" label-width="110px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="所属事业部" prop="department">
            <span v-if="handle == 'detail'">{{ editForm.department }}</span>
            <el-select
              v-else
              v-model="editForm.department"
              placeholder="选择订单所属事业部"
              clearable
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in divisionList"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="报销人" prop="user_name">
            {{ editForm.user_name || "" }}
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="日期" prop="created_time">
            {{ editForm.created_time }}
          </el-form-item>
        </el-col>
      </el-row>
      <div style="margin-bottom: 20px">
        <div v-if="handle != 'detail'" style="margin-bottom: 20px">
          <el-button type="primary" icon="el-icon-plus" @click="addData">新增</el-button>
        </div>
        <el-table :data="dataList" border style="width: 100%">
          <el-table-column label="序号" type="index" width="60" align="center" />
          <el-table-column label="回款编号" align="center">
            <template slot-scope="scope">
              <span
                v-if="handle == 'detail'"
                :style="showDetail ? 'color: #409eff; cursor: pointer' : ''"
                @click="handleContract(scope.row)"
              >
                {{ scope.row.order_sn }}
              </span>
              <el-select
                v-else
                v-model="scope.row.order_sn"
                filterable
                remote
                class="receivable"
                :clearable="false"
                placeholder="请检索"
                :remote-method="(e) => getReceivable(e, scope.$index)"
                @change="changeReceipt(scope.row.receiptList, scope.$index)"
              >
                <el-option
                  v-for="item in scope.row.receiptList"
                  :key="item.order_sn"
                  :label="item.order_sn"
                  :value="item.order_sn"
                  :disabled="dataList.some((i) => i.order_sn == item.order_sn)"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="客户名称" align="center" prop="customer_name" />
          <el-table-column label="费用类别" align="center">
            <template slot-scope="scope">
              <span v-if="handle == 'detail'">{{ scope.row.expense_type }}</span>
              <el-select v-else v-model="scope.row.expense_type" placeholder="请选择">
                <el-option
                  v-for="(item, k) in typeList"
                  :key="scope.$index + '_' + k"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="成本" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.cost_money_all }}</span>
            </template>
          </el-table-column>
          <el-table-column label="可使用成本" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.cost_money }}</span>
            </template>
          </el-table-column>
          <el-table-column label="办理事项描述" align="center">
            <template slot-scope="scope">
              <span v-if="handle == 'detail'">{{ scope.row.ramark }}</span>
              <el-input
                v-else
                v-model="scope.row.ramark"
                type="textarea"
                :autosize="{ minRows: 1, maxRows: 3 }"
                placeholder="请输入"
              />
            </template>
          </el-table-column>
          <el-table-column label="报销金额" align="center">
            <template slot-scope="scope">
              <span v-if="handle == 'detail'">{{ scope.row.money }}元</span>
              <el-input-number
                v-else
                v-model="scope.row.money"
                type="number"
                :max="parseFloat(scope.row.cost_money || '0')"
                :min="0"
                :precision="2"
                :controls="false"
                placeholder="请输入"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column
            v-if="handle != 'detail'"
            label="操作"
            align="center"
            width="80"
          >
            <template slot-scope="scope">
              <el-button
                type="danger"
                icon="el-icon-minus"
                size="small"
                circle
                @click="delData(scope.$index)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="报销总金额" prop="total_money">
            {{ editForm.total_money }}元
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="金额大写" prop="upper">
            {{ editForm.upper }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="收款人" prop="payee">
            <span v-if="handle == 'detail'">{{ editForm.payee }}</span>
            <el-input
              v-else
              v-model="editForm.payee"
              placeholder="请输入收款人"
              maxlength="50"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开户行" prop="opening_bank">
            <span v-if="handle == 'detail'">{{ editForm.opening_bank }}</span>
            <el-input
              v-else
              v-model="editForm.opening_bank"
              placeholder="请输入"
              maxlength="50"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="银行账号" prop="bank_number">
            <span v-if="handle == 'detail'">{{ editForm.bank_number }}</span>
            <el-input
              v-else
              v-model="editForm.bank_number"
              placeholder="请输入"
              maxlength="50"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="附件" prop="attachment">
            <div v-if="handle == 'detail'">
              <img
                v-for="(i, k) in fileList"
                :key="k"
                :src="i"
                class="atta-img"
                @click="previewImage(k)"
              />
            </div>
            <el-upload
              v-else
              ref="fileUpload"
              :action="crmFileSaveUrl"
              :headers="httpHeader"
              name="file[]"
              multiple
              accept="image/*"
              :before-upload="beforeUpload"
              :on-success="fileUploadSuccess"
              :file-list="fileList"
            >
              <p>
                <img
                  src="@/assets/img/relevance_file.png"
                  style="vertical-align: middle"
                />
                上传附件
              </p>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button
        v-if="handle != 'detail'"
        type="primary"
        :loading="loading"
        @click="submitForm"
      >
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>
<script>
import moment from "moment";
import axios from "axios";
import { mapGetters } from "vuex";
import { crmFileSaveUrl } from "@/api/common";
import {
  saveExpence,
  getFinanceCode,
  updateExpence,
} from "@/api/customermanagement/expence";
import { getDivisionData } from "@/api/systemManagement/division";
import { getExpenceClassData } from "@/api/systemManagement/expenceClass";

import { numberToChinese } from "@/utils/index";
export default {
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    form: {
      type: Object,
      default: () => {},
    },
    showDetail: {
      type: Boolean,
      default: false,
    },
    handle: {
      type: String,
      default: "detail",
    },
  },
  data() {
    return {
      editForm: {
        department: "", // 部门
        created_time: "", // 日期
        user_name: "", // 报销人
        detail: [], // 报销订单列表
        total_money: "", // 总金额
        upper: "", // 大写金额
        payee: "", // 收款人
        opening_bank: "", // 开户行
        bank_number: "", // 银行账号
        attachment: "", // 附件
      },
      dataList: [], // 报销订单列表
      fileList: [], // 附件列表
      formRules: {
        department: [{ required: true, message: "请选择部门", trigger: "change" }],
        payee: [{ required: true, message: "请输入收款人", trigger: "blur" }],
        opening_bank: [{ required: true, message: "请输入开户行", trigger: "blur" }],
        bank_number: [{ required: true, message: "请输入银行账号", trigger: "blur" }],
      },
      loading: false, // 加载状态
      divisionList: [], // 部门列表
      typeList: [], // 费用类别列表
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
    show: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit("input", val);
      },
    },
    // 附件上传地址
    crmFileSaveUrl() {
      return window.BASE_URL + crmFileSaveUrl;
    },
    // 请求头
    httpHeader() {
      return {
        authKey: axios.defaults.headers.authKey,
        sessionId: axios.defaults.headers.sessionId,
      };
    },
  },
  watch: {
    value(val) {
      if (val) {
        this.$nextTick(async () => {
          await this.getDivisionList()
          await this.getExpenceClassList()
          if (this.form.id) {
            Object.keys(this.form).forEach((key) => {
              if (this.form[key]) {
                this.editForm[key] = this.form[key];
              }
            });
            this.dataList = this.form.detail || [];
            this.dataList.forEach((item, index) => {
              item.expense_type = item.type;
              this.getReceivable(item.order_sn, index);
            });
            this.fileList = this.form.attachment
              ? this.form.attachment.split(",").filter(Boolean)
              : [];

            this.editForm.created_time = moment(this.editForm.created_time).format(
              "YYYY-MM-DD"
            );
          } else {
            this.editForm.created_time = moment().format("YYYY-MM-DD");
            this.editForm.user_name = this.userInfo.realname;
          }
        });
      }
    },
    dataList: {
      handler(val) {
        let money = 0;
        val.forEach((item) => {
          money += parseFloat(item.money || "0");
        });
        this.editForm.total_money = money.toFixed(2);
        this.editForm.upper = numberToChinese(money);
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    // 获取事业部列表
    getDivisionList() {
      return new Promise((resolve) => {
        getDivisionData().then(res => {
          let list = res.data.list;
          list = list.map(item => item.name)
          this.divisionList = list
          resolve()
        }).catch(() => {
          this.divisionList = []
          resolve()
        })
      })
    },
    // 获取费用类别列表
    getExpenceClassList() {
      return new Promise((resolve) => {
        getExpenceClassData().then(res => {
          let list = res.data.list || [];
          list = list.map(item => item.name)
          this.typeList = list
          resolve()
        }).catch(() => {
          this.typeList = []
          resolve()
        })
      })
    },
    // 关闭弹窗
    dialogClose() {
      this.show = false;
      this.loading = false;
      this.dataList = [];
      this.fileList = [];
      this.editForm = {
        department: "", // 部门
        created_time: "", // 日期
        user_name: "", // 报销人
        detail: [], // 报销订单列表
        total_money: "", // 总金额
        upper: "", // 大写金额
        payee: "", // 收款人
        opening_bank: "", // 开户行
        bank_number: "", // 银行账号
        attachment: "", // 附件
      };
      this.$refs.formRef.resetFields();
      this.$emit("on-close");
    },
    // 新增报销订单
    addData() {
      this.dataList.push({
        order_sn: "", // 回款编号
        receiptList: [], // 回款编号列表
        customer_name: "", // 客户名称
        expense_type: "", // 费用类别
        cost_money: "", // 可使用成本
        cost_money_all: "", // 成本
        ramark: "", // 描述
        money: "", // 金额
      });
    },
    // 删除报销订单
    delData(index) {
      this.dataList.splice(index, 1);
    },
    // 查看详情
    handleContract(row) {
      if (!this.showDetail) return;
      this.$emit("on-detail", row);
    },
    // 获取回款编号列表
    getReceivable(order_sn = "", index) {
      if (this.handle === "add") {
        this.dataList[index].receiptList = [];
        this.dataList[index].order_sn = "";
        this.dataList[index].customer_name = "";
        this.dataList[index].cost_money = "";
        this.dataList[index].cost_money_all = "";
        this.dataList[index].money = "";
      }
      if (order_sn) {
        getFinanceCode({ order_sn }).then((res) => {
          this.dataList[index].receiptList = res.data || [];
          if (this.handle === 'edit') {
            let row = res.data.find((item) => item.order_sn == order_sn);
            this.dataList[index].cost_money = row.max_expense_money;
          }
        });
      } else {
        this.dataList[index].receiptList = [];
      }
    },
    // 切换回款编号获取可使用成本
    changeReceipt(options = [], index) {
      let order_sn = this.dataList[index].order_sn;
      let row = options.find((item) => item.order_sn == order_sn);
      this.dataList[index].customer_name = row.customer_name;
      this.dataList[index].cost_money = row.max_expense_money;
      this.dataList[index].cost_money_all = row.crm_oeseng;
      this.dataList[index].money = parseFloat(row.max_expense_money);
    },
    // 校验
    beforeUpload(file) {
      let size = file.size / 1024 / 1024;
      if (size > 100) {
        this.$message.error("文件大小不能超过100M");
        return false;
      }
      let type = file.name.split(".")[1];
      let types = ["jpg", "png", "jpeg", "gif", "bmp"];
      if (!types.includes(type)) {
        this.$message.error("文件格式不正确");
        return false;
      }
      return true;
    },
    // 上传成功
    fileUploadSuccess(res, file, fileList) {
      this.fileList = fileList;
    },
    // 预览图片
    previewImage(index) {
      this.$bus.emit("preview-image-bus", {
        index: index,
        data: this.fileList.map((item) => {
          return {
            url: item,
            name: item.substr(item.lastIndexOf("/") + 1),
          };
        }),
      });
    },
    // 提交表单
    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          let data = Object.assign({}, this.editForm);
          if (Number(data.total_money) === 0) {
            this.$message.error("报销总金额不能为0");
            return;
          }
          data.detail = this.dataList
            .filter((i) => i.order_sn)
            .map(({ receiptList, contract_id, expence_id, type, id, ...i }) => i);
          if (this.fileList.length > 0) {
            let urls = this.fileList.map((i) => i.response.data.length > 0 && i.response.data[0].path);
            data.attachment = urls.join(",");
          }
          if (this.handle === "edit") {
            delete data.examineRecord;
            delete data.examine_id;
            delete data.upload_time;
            delete data.user_id;
            delete data.order_sn;
          }
          const request = this.handle === "add" ? saveExpence : updateExpence;
          this.loading = true;
          request(data)
            .then((res) => {
              this.$message.success(res.data || "操作成功");
              this.$emit("on-success");
              this.dialogClose();
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.atta-img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  margin-bottom: 10px;
  margin-right: 10px;
}
::v-deep .receivable .el-input--suffix .el-input__inner {
  padding-right: 8px !important;
}
</style>
